package com.jinlejia.erp.ui.new_house.house;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.android.material.tabs.TabLayout;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityHousePhotosBinding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.new_house.adapter.HousePhtotsAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;

/***
 *楼盘相册*/
public class HousePhotosActivity extends AppCompatActivity {
    private ActivityHousePhotosBinding binding;
    private String houseCode;
    private ProgressDialog progressDialog;
    private HousePhtotsAdapter housePhtotsAdapter1, housePhtotsAdapter2, housePhtotsAdapter3, housePhtotsAdapter4;
    private ArrayList<Map<String, Object>> designSketchList = new ArrayList<>();//效果图集合
    private ArrayList<Map<String, Object>> realPictureList = new ArrayList<>();//实景图集合
    private ArrayList<Map<String, Object>> modelRoomList = new ArrayList<>();//样板间集合
    private ArrayList<Map<String, Object>> supportingDrawingList = new ArrayList<>();//配套图集合
    private int height1, height2, height3, height4;
    private ArrayList<String> imgList1 = new ArrayList<>();
    private ArrayList<String> imgList2 = new ArrayList<>();
    private ArrayList<String> imgList3 = new ArrayList<>();
    private ArrayList<String> imgList4 = new ArrayList<>();
    private boolean IsSlide = false;//默认不是滑动操作

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_house_photos);
        binding.setEvent(this);
        progressDialog = new ProgressDialog(this, "请稍后...",false);
        progressDialog.show();
        houseCode = getIntent().getStringExtra("houseCode");

        //region 效果图列表
        binding.recyclerview1.setHasFixedSize(true);
        binding.recyclerview1.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false));
        binding.recyclerview1.setNestedScrollingEnabled(false);
        housePhtotsAdapter1 = new HousePhtotsAdapter(designSketchList);
        binding.recyclerview1.setAdapter(housePhtotsAdapter1);
        //endregion

        //region 实景图列表
        binding.recyclerview2.setHasFixedSize(true);
        binding.recyclerview2.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false));
        binding.recyclerview2.setNestedScrollingEnabled(false);
        housePhtotsAdapter2 = new HousePhtotsAdapter(realPictureList);
        binding.recyclerview2.setAdapter(housePhtotsAdapter2);
        //endregion

        //region 样板间列表
        binding.recyclerview3.setHasFixedSize(true);
        binding.recyclerview3.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false));
        binding.recyclerview3.setNestedScrollingEnabled(false);
        housePhtotsAdapter3 = new HousePhtotsAdapter(modelRoomList);
        binding.recyclerview3.setAdapter(housePhtotsAdapter3);
        //endregion

        //region 配套图列表
        binding.recyclerview4.setHasFixedSize(true);
        binding.recyclerview4.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false));
        binding.recyclerview4.setNestedScrollingEnabled(false);
        housePhtotsAdapter4 = new HousePhtotsAdapter(supportingDrawingList);
        binding.recyclerview4.setAdapter(housePhtotsAdapter4);
        //endregion

        binding.idTableLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //当标签处于选中的状此时有两种情况
                // 1.直接点击tabLayout标签会走
                // 2.当ScrollView滑动时，因为我们在滑动里面设置了选择标签，所以此时这个方法也会走
                //现在有个问题，当滑动的时候，tabLayout标签也会被选择，这个方法也会走，所以此时会产生冲突，我们要排除滑动的操作
                if (IsSlide) {//表示此时正在滑动  不走这个方法
                    return;
                }
                String title = String.valueOf(tab.getText());
                if (title.contains("效果")) {
                    binding.nestedScrollView.smoothScrollTo(0, 0);//滑到对应的View顶部
                } else if (title.contains("实景")) {
                    binding.nestedScrollView.smoothScrollTo(0, height1);//滑到对应的View顶部
                } else if (title.contains("样板")) {
                    binding.nestedScrollView.smoothScrollTo(0, height2);//滑到对应的View顶部
                } else if (title.contains("配套")) {
                    binding.nestedScrollView.fullScroll(NestedScrollView.FOCUS_DOWN);//滚动到底部
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        binding.nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                IsSlide = true;//表明此时正在滑动
                View contentView = v.getChildAt(0);
                if (scrollY < height1) {//表明此时在Item1范围内，所以第一个Item应该被选择
                    Objects.requireNonNull(binding.idTableLayout.getTabAt(0)).select();
                } else if (scrollY >= height1 && scrollY < height2) {//表明此时在Item2范围内，所以第二个Item应该被选择
                    Objects.requireNonNull(binding.idTableLayout.getTabAt(1)).select();
                } else if (contentView.getMeasuredHeight() == v.getScrollY() + v.getHeight()) {//表明此时滑动到底部所以第四个Item被选择
                    Objects.requireNonNull(binding.idTableLayout.getTabAt(binding.idTableLayout.getTabCount()-1)).select();
                } else if (scrollY >= height2 && scrollY < height3) {//表明此时在Item3范围内，所以第三个Item应该被选择
                    Objects.requireNonNull(binding.idTableLayout.getTabAt(2)).select();
                }
                IsSlide = false;//表明滑动结束
            }
        });

        housePhtotsAdapter1.setItemOnclick(new HousePhtotsAdapter.ItemOnclick() {
            @Override
            public void onitemClick(int position) {
                Intent intent = new Intent(HousePhotosActivity.this, ViewPagerActivity.class);
                intent.putStringArrayListExtra("imgs", imgList1);
                intent.putExtra("position", position);
                intent.putExtra("title", "效果图");
                startActivity(intent);
            }
        });

        housePhtotsAdapter2.setItemOnclick(new HousePhtotsAdapter.ItemOnclick() {
            @Override
            public void onitemClick(int position) {
                Intent intent = new Intent(HousePhotosActivity.this, ViewPagerActivity.class);
                intent.putStringArrayListExtra("imgs", imgList2);
                intent.putExtra("position", position);
                intent.putExtra("title", "实景图");
                startActivity(intent);
            }
        });

        housePhtotsAdapter3.setItemOnclick(new HousePhtotsAdapter.ItemOnclick() {
            @Override
            public void onitemClick(int position) {
                Intent intent = new Intent(HousePhotosActivity.this, ViewPagerActivity.class);
                intent.putStringArrayListExtra("imgs", imgList3);
                intent.putExtra("position", position);
                intent.putExtra("title", "样板间");
                startActivity(intent);
            }
        });

        housePhtotsAdapter4.setItemOnclick(new HousePhtotsAdapter.ItemOnclick() {
            @Override
            public void onitemClick(int position) {
                Intent intent = new Intent(HousePhotosActivity.this, ViewPagerActivity.class);
                intent.putStringArrayListExtra("imgs", imgList4);
                intent.putExtra("position", position);
                intent.putExtra("title", "配套图");
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
       getData();
    }

    private void getData() {
        OkHttpUtils.get().url(ApiConfig.HOUSEPAN_ALL_PHTOTS)
                .addParams("houseCode", houseCode)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(HousePhotosActivity.this, response)) {
                            designSketchList.clear();
                            realPictureList.clear();
                            modelRoomList.clear();
                            supportingDrawingList.clear();
                            imgList1.clear();
                            imgList2.clear();
                            imgList3.clear();
                            imgList4.clear();
                            binding.idTableLayout.removeAllTabs();
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            ArrayList<Map<String, Object>> housespicList = (ArrayList<Map<String, Object>>) JSON.parseObject(String.valueOf(data.get("housespicList")), new TypeReference<List<Map<String, Object>>>() {
                            });
                            for (Map<String, Object> map : housespicList) {
                                int imageType = Integer.parseInt(String.valueOf(map.get("imageType")));
                                if (imageType == 1) {
                                    designSketchList.add(map);
                                    imgList1.add(String.valueOf(map.get("imageUrl")));
                                } else if (imageType == 2) {
                                    realPictureList.add(map);
                                    imgList2.add(String.valueOf(map.get("imageUrl")));
                                } else if (imageType == 3) {
                                    modelRoomList.add(map);
                                    imgList3.add(String.valueOf(map.get("imageUrl")));
                                } else if (imageType == 4) {
                                    supportingDrawingList.add(map);
                                    imgList4.add(String.valueOf(map.get("imageUrl")));
                                }
                            }

                            if (designSketchList.size() != 0) {
                                binding.idTableLayout.addTab(binding.idTableLayout.newTab().setText("效果图(" + designSketchList.size() + ")"));
                                housePhtotsAdapter1.setData(designSketchList);
                                housePhtotsAdapter1.notifyDataSetChanged();
                                binding.layoutItem1.setVisibility(View.VISIBLE);
                            } else {
                                binding.layoutItem1.setVisibility(View.GONE);
                                binding.idTableLayout.addTab(binding.idTableLayout.newTab().setText("效果图(0)"));
                            }

                            if (realPictureList.size() != 0) {
                                binding.idTableLayout.addTab(binding.idTableLayout.newTab().setText("实景图(" + realPictureList.size() + ")"));
                                housePhtotsAdapter2.setData(realPictureList);
                                housePhtotsAdapter2.notifyDataSetChanged();
                                binding.layoutItem2.setVisibility(View.VISIBLE);
                            } else {
                                binding.layoutItem2.setVisibility(View.GONE);
                                binding.idTableLayout.addTab(binding.idTableLayout.newTab().setText("实景图(0)"));
                            }

                            if (modelRoomList.size() != 0) {
                                binding.idTableLayout.addTab(binding.idTableLayout.newTab().setText("样板间(" + modelRoomList.size() + ")"));
                                housePhtotsAdapter3.setData(modelRoomList);
                                housePhtotsAdapter3.notifyDataSetChanged();
                                binding.layoutItem3.setVisibility(View.VISIBLE);
                            } else {
                                binding.layoutItem3.setVisibility(View.GONE);
                                binding.idTableLayout.addTab(binding.idTableLayout.newTab().setText("样板间(0)"));
                            }

                            if (supportingDrawingList.size() != 0) {
                                binding.idTableLayout.addTab(binding.idTableLayout.newTab().setText("配套图(" + supportingDrawingList.size() + ")"));
                                housePhtotsAdapter4.setData(supportingDrawingList);
                                housePhtotsAdapter4.notifyDataSetChanged();
                                binding.layoutItem4.setVisibility(View.VISIBLE);
                            } else {
                                binding.layoutItem4.setVisibility(View.GONE);
                                binding.idTableLayout.addTab(binding.idTableLayout.newTab().setText("配套图(0)"));
                            }
                        }
                    }
                });
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.id_back:
                finish();
                break;
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        height1 = binding.layoutItem1.getMeasuredHeight();//表示第一个item的高度,这是高度
        height2 = binding.layoutItem1.getMeasuredHeight() + binding.layoutItem2.getMeasuredHeight();//这个是第一个item加第二个item的高度  下面同理
        height3 = binding.layoutItem1.getMeasuredHeight() + binding.layoutItem2.getMeasuredHeight() + binding.layoutItem3.getMeasuredHeight();
        height4 = binding.layoutItem1.getMeasuredHeight() + binding.layoutItem2.getMeasuredHeight() + binding.layoutItem3.getMeasuredHeight() + binding.layoutItem4.getMeasuredHeight();
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}